<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 头部提示区域 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 列表区域 -->
      <el-row>
        <el-col class="cat_opt">
          <span>选择商品分类：</span>
          <!-- // 级联选择器 -->
          <el-cascader
            v-model="seletedkeys"
            :options="CateList"
            :props="cascaderProps"
            @change="cascaderChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 参数区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加按钮 -->
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="addDialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格区域 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="addDialogVisible = true"
          >
            添加属性
          </el-button>
          <!-- 静态属性表格区域 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="addFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'ParamsPage',
  data() {
    return {
      // 所有分类展示数据
      CateList: [],
      // 级联选择器选项配置
      cascaderProps: {
        expandTrigger: 'hover' /* 新版element要写在这里 */,
        value: 'cat_id' /* 选中的是哪个属性 */,
        label: 'cat_name' /* 显示的是哪个属性 */,
        children: 'children' /* 嵌套的是哪个属性 */
      },
      // 级联选择器选中的id
      seletedkeys: [],
      // 切换栏默认显示的那一栏
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 添加属性对话框是否显示
      addDialogVisible: false,
      // 添加属性的表单
      addForm: {
        attr_name: ''
      },
      // 添加属性的表单验证规则
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名',
            trigger: 'blur'
          }
        ]
      },
      // 修改参数对话框是否显示
      editDialogVisible: false,
      editForm: {}
    }
  },
  methods: {
    async getGoodsList() {
      // 调用接口获取商品分类列表
      const { data: res } = await this.$http.get('categories')
      // 判断是否获取成功
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      // 获取成功保存起来
      this.CateList = res.data
    },
    // 级联选择器发生变化
    cascaderChange() {
      // console.log(this.seletedkeys)
      this.getParamsData()
    },
    // 监听tabs发生切换
    handleTabsClick() {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 根据级联选择器的选择请求参数
    async getParamsData() {
      // 证明选中的不是三级分类 清空选中 使得不让选中 只可以选中三级分类 同时下方的数据（上次遗留的数据）也清空 要不然上次打开的数据还能用
      if (this.seletedkeys.length !== 3) {
        this.seletedkeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.CateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      // 获取成功后，需要进行判断
      // console.log(res.data)
      // 获取展开行数据
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // console.log(item.attr_vals)
        // 给每一行的数据都添加一个单独的inputVisible inputValue
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 添加属性对话框关闭后
    addDialogClosed() {
      // 清空对话框里表单内容
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮添加属性
    addParams() {
      // 先预校验表单
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        // 表单验证通过后发起请求
        const { data: res } = await this.$http.post(
          `categories/${this.CateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // 发起请求后判断请求结果
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        // 请求正确后  提示成功 关闭对话框 刷新参数列表
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 修改参数对话框关闭后
    editDialogClosed() {
      // 清空对话框里表单内容
      this.$refs.editFormRef.resetFields()
    },
    // 展示修改参数对话框
    async showEditDialog(attrId) {
      // 点击后，获取该id的数据
      const { data: res } = await this.$http.get(
        `categories/${this.CateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      // 发起请求后判断请求结果
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      // 请求正确后
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改参数
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        // 表单验证通过后发起请求
        const { data: res } = await this.$http.put(
          `categories/${this.CateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // 发起请求后判断请求结果
        if (res.meta.status !== 200) {
          return this.$message.error('添加参数失败')
        }
        // 请求正确后  提示成功 关闭对话框 刷新参数列表
        this.$message.success('添加参数成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除参数
    async removeParams(attrID) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      // 确定删除，发起请求
      const { data: res } = await this.$http.delete(
        `categories/${this.CateId}/attributes/${attrID}`
      )
      //
      if (res.meta.status !== 200) {
        this.$message.error('删除参数失败')
      }
      // 成功后
      this.$message.success('删除参数成功')
      this.getParamsData()
    },
    // 添加标签的输入框失去焦点时
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        // 说明输入为空
        // 清空表单
        row.inputValue = ''
        // 关闭输入框
        row.inputVisible = false
        return
      }
      // 如果不为空，说明有进行输入,保存到数据中
      row.attr_vals.push(row.inputValue.trim())
      // 清空表单
      row.inputValue = ''
      // 关闭输入框
      row.inputVisible = false
      this.saveChangeData(row)
    },
    // 保存数据到后台
    async saveChangeData(row) {
      // 保存数据到后台
      const { data: res } = await this.$http.put(
        `categories/${this.CateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      // console.log(row)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }
      this.$message.success('修改参数项成功！')
    },
    // 添加按钮的点击事件
    showInput(row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签
    handleClose(i, row) {
      // 先将数组中对应索引的数据删除，然后保存到后台
      row.attr_vals.splice(i, 1)
      this.saveChangeData(row)
    }
  },
  created() {
    this.getGoodsList()
  },
  computed: {
    // 是否禁用
    isDisabled() {
      if (this.seletedkeys.length !== 3) {
        return true
      }
      return false
    },
    // 被选中的三级ID
    CateId() {
      if (this.seletedkeys.length === 3) {
        return this.seletedkeys[2]
      }
      return null
    },
    // 添加参数的名字
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
